<template>
  <div class="container">
    <a-card title="角色管理" :bordered="false">
      <a-space style="margin-bottom: 16px">
        <a-button type="primary" @click="handleCreate">
          <template #icon>
            <icon-plus/>
          </template>
          新建角色
        </a-button>
      </a-space>

      <a-table
        :columns="columns"
        :data="roleList"
        :loading="loading"
        row-key="id"
      >
        <template #actions="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="handleEdit(record)">
              <template #icon>
                <icon-edit/>
              </template>
              编辑
            </a-button>
            <a-popconfirm
              content="确定要删除这个角色吗？"
              @ok="handleDelete(record.id)"
            >
              <a-button type="text" status="danger" size="small">
                <template #icon>
                  <icon-delete/>
                </template>
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <a-modal
      v-model:visible="modalVisible"
      :title="isEditMode ? '编辑角色' : '新建角色'"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      :on-before-ok="submitForm"
    >
      <a-form ref="formRef" :model="form">
        <a-form-item
          field="roleName"
          label="角色名称"
          :rules="[{ required: true, message: '请输入角色名称' }]"
        >
          <a-input v-model="form.roleName"/>
        </a-form-item>
        <a-form-item
          field="roleCode"
          label="角色编码"
          :rules="[{ required: true, message: '请输入角色编码' }]"
        >
          <a-input v-model="form.roleCode"/>
        </a-form-item>
        <a-form-item field="description" label="角色描述">
          <a-textarea v-model="form.description"/>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue'
import {createRoleApi, deleteRoleApi, getAllRolesApi, updateRoleApi} from '@/api/role'
import type {Role, RoleRequest} from '@/types/api/role'
import {type FormInstance, Message} from '@arco-design/web-vue'
import {IconDelete, IconEdit, IconPlus} from '@arco-design/web-vue/es/icon'

// -- 状态定义 --
const loading = ref(false)
const roleList = ref<Role[]>([])
const modalVisible = ref(false)
const isEditMode = ref(false)
const formRef = ref<FormInstance | null>(null)
const currentEditId = ref<number | null>(null)

const defaultForm: RoleRequest = {
  roleName: '',
  roleCode: '',
  description: ''
}
const form = reactive<RoleRequest>({...defaultForm})

// -- 表格列定义 --
const columns = [
  {title: 'ID', dataIndex: 'id', width: 80},
  {title: '角色名称', dataIndex: 'roleName'},
  {title: '角色编码', dataIndex: 'roleCode'},
  {title: '描述', dataIndex: 'description'},
  {title: '操作', slotName: 'actions', width: 180, align: 'center'}
]

// -- API 调用 --
const fetchRoles = async () => {
  loading.value = true
  try {
    const data = await getAllRolesApi()
    roleList.value = data
  } catch (error) {
    Message.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// -- 生命周期钩子 --
onMounted(() => {
  fetchRoles()
})

// -- 事件处理 --
const resetForm = () => {
  Object.assign(form, defaultForm)
  currentEditId.value = null
}

const handleCreate = () => {
  resetForm()
  isEditMode.value = false
  modalVisible.value = true
}

const handleEdit = (record: Role) => {
  isEditMode.value = true
  currentEditId.value = record.id
  // 将 'Role' 对象的属性复制到 'RoleRequest' DTO
  form.roleName = record.roleName
  form.roleCode = record.roleCode
  form.description = record.description || ''
  modalVisible.value = true
}

const handleDelete = async (id: number) => {
  try {
    await deleteRoleApi(id)
    Message.success('删除成功')
    await fetchRoles() // 刷新列表
  } catch (error) {
    Message.error('删除失败')
  }
}

const handleModalCancel = () => {
  modalVisible.value = false
  resetForm()
}

// 弹窗表单提交
const submitForm = async () => {
  const validateError = await formRef.value?.validate()
  if (validateError) {
    return false // 阻止弹窗关闭
  }

  try {
    if (isEditMode.value && currentEditId.value) {
      await updateRoleApi(currentEditId.value, form)
      Message.success('更新成功')
    } else {
      await createRoleApi(form)
      Message.success('创建成功')
    }
    await fetchRoles() // 刷新列表
    return true // 允许弹窗关闭
  } catch (error) {
    Message.error('操作失败')
    return false // 阻止弹窗关闭
  }
}

// 弹窗关闭后重置
const handleModalOk = () => {
  handleModalCancel()
}
</script>

<style scoped>
.container {
  padding: 20px;
}
</style>
